<template>
  <view>
    <view class="chat-container">
      <view class="chat-top">
        <scroll-view scroll-y class="chat-messages" :scroll-top="scrollTop">
          <view v-if="messages.length === 0" class="welcome-tips">
            <view class="welcome-header">
              <view class="ai-logo">
                <text>AI</text>
              </view>
              <text class="welcome-title">智能助手</text>
            </view>
            <view class="tips-content">
              <text class="greeting-text">你好，我是AI助手👋</text>
              <text class="intro-text"
                >我可以回答你的问题，提供校园信息，或者陪你聊天放松一下~</text
              >
            </view>
            <view class="quick-actions">
              <view
                class="quick-action-item"
                @click="quickAsk('学校有哪些社团？')"
              >
                <view class="action-icon">👥</view>
                <text>社团活动</text>
              </view>
              <view
                class="quick-action-item"
                @click="quickAsk('食堂有什么好吃的？')"
              >
                <view class="action-icon">🍲</view>
                <text>美食推荐</text>
              </view>
            </view>
          </view>
          <view v-else class="message-list">
            <view
              v-for="(item, index) in messages"
              :key="index"
              class="message-item"
              :class="item.type === 'user' ? 'message-user' : 'message-ai'"
            >
              <view
                class="message-avatar"
                :class="item.type === 'user' ? 'user-avatar' : 'ai-avatar'"
              >
                <text>{{ item.type === "user" ? "我" : "AI" }}</text>
              </view>
              <view
                class="message-content"
                :class="item.type === 'user' ? 'user-content' : 'ai-content'"
              >
                <text>{{ item.content }}</text>
              </view>
            </view>
            <!-- 添加思考中状态显示 -->
            <view v-if="thinking" class="message-item message-ai">
              <view class="message-avatar ai-avatar">
                <text>AI</text>
              </view>
              <view class="message-content ai-content thinking">
                <text>思考中...</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="chat-bottom">
        <textarea
          class="chat-input"
          v-model="inputMessage"
          placeholder="请输入消息..."
          :disabled="loading"
        />
        <view
          class="chat-sendBottom"
          :class="{ 'send-disabled': !inputMessage.trim() || loading }"
          @click="sendMessage"
        >
          <text>{{ loading ? "..." : "发送" }}</text>
        </view>
      </view>
    </view>
    <view class="bottom">湘ICP备2025114942号</view>
  </view>
</template>

<script setup>
  import { ref, reactive, nextTick } from "vue";
  import { API_CONFIG } from "../../config/api.js";

  // 聊天消息列表
  const messages = reactive([]);
  // 输入框内容
  const inputMessage = ref("");
  // 加载状态
  const loading = ref(false);
  // 滚动位置
  const scrollTop = ref(0);
  const conversation_id = ref("");
  const chat_id = ref("");

  // 快速提问功能
  const quickAsk = (question) => {
    if (loading.value) return;
    inputMessage.value = question;
    sendMessage();
  };

  // 添加思考状态
  const thinking = ref(false);

  // 发送消息
  const sendMessage = async () => {
    const message = inputMessage.value.trim();
    if (!message || loading.value) return;

    try {
      loading.value = true;
      thinking.value = true; // 设置思考状态
      messages.push({
        type: "user",
        content: message,
      });
      inputMessage.value = "";
      scrollToBottom();

      const response = await uni.request({
        url: `${API_CONFIG.COZE.BASE_URL}/chat`,
        method: "POST",
        header: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${API_CONFIG.COZE.TOKEN}`,
        },
        data: {
          bot_id: API_CONFIG.COZE.BOT_ID,
          user_id: "123123",
          additional_messages: [
            {
              content: message,
              role: "user",
            },
          ],
        },
      });

      conversation_id.value = response.data.data.conversation_id;
      chat_id.value = response.data.data.id;

      // 轮询检查状态，带有重试机制
      let retryCount = 0;
      const maxRetries = 3;
      const maxPollingAttempts = 10;
      const pollingInterval = 2000;
      let pollingCount = 0;

      while (pollingCount < maxPollingAttempts) {
        try {
          const statusResponse = await uni.request({
            url: `${API_CONFIG.COZE.BASE_URL}/chat/retrieve?conversation_id=${conversation_id.value}&chat_id=${chat_id.value}`,
            method: "POST",
            header: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${API_CONFIG.COZE.TOKEN}`,
            },
            data: {},
          });

          if (statusResponse.data.data.status === "completed") {
            const messageResponse = await uni.request({
              url: `${API_CONFIG.COZE.BASE_URL}/chat/message/list?conversation_id=${conversation_id.value}&chat_id=${chat_id.value}`,
              method: "GET",
              header: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${API_CONFIG.COZE.TOKEN}`,
              },
            });

            const completeMessage = messageResponse.data.data[0].content;
            if (completeMessage) {
              messages.push({
                type: "ai",
                content: completeMessage,
              });
              thinking.value = false; // 成功获取回复后重置思考状态
              break;
            } else {
              throw new Error("无法获取AI回复内容");
            }
          }

          await new Promise((resolve) => setTimeout(resolve, pollingInterval));
          pollingCount++;
        } catch (error) {
          if (retryCount < maxRetries) {
            retryCount++;
            await new Promise((resolve) => setTimeout(resolve, 1000));
            continue;
          }
          throw error;
        }
      }

      if (pollingCount >= maxPollingAttempts) {
        throw new Error("响应超时，请重试");
      }
    } catch (error) {
      thinking.value = false; // 发生错误时也要清除思考状态
      console.error("消息处理失败:", error);
      messages.push({
        type: "ai",
        content: error.message || "抱歉，服务出现异常，请稍后再试",
      });
    } finally {
      loading.value = false;
      scrollToBottom();
    }
  };

  // 滚动到底部
  const scrollToBottom = () => {
    nextTick(() => {
      scrollTop.value = 9999999;
    });
  };
</script>

<style lang="scss">
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10rpx);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .chat-container {
    height: 770rpx;
    width: 90%;
    margin: auto;
    border-radius: 32rpx;
    position: relative;
    overflow: hidden;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    // background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%);
    // border: 1px solid rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    .chat-top {
      border-radius: 32rpx 32rpx 0 0;
      width: 100%;
      height: 75%;
      // background-color: rgba(255, 255, 255, 0.9);
      position: relative;
      overflow: hidden;

      .chat-messages {
        height: 100%;
        padding: 24rpx;
        box-sizing: border-box;

        // 微信小程序隐藏滚动条
        ::-webkit-scrollbar {
          width: 0;
          height: 0;
          color: transparent;
        }
      }

      .welcome-tips {
        display: flex;
        flex-direction: column;
        height: 100%;
        justify-content: flex-start;
        align-items: center;
        padding: 30rpx 20rpx;

        .welcome-header {
          display: flex;
          align-items: center;
          margin-bottom: 30rpx;

          .ai-logo {
            width: 80rpx;
            height: 80rpx;
            border-radius: 20rpx;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16rpx;
            box-shadow: 0 6rpx 16rpx rgba(106, 17, 203, 0.3);

            text {
              color: white;
              font-size: 36rpx;
              font-weight: bold;
            }
          }

          .welcome-title {
            font-size: 36rpx;
            font-weight: bold;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            -webkit-background-clip: text;
            color: transparent;
          }
        }

        .tips-content {
          width: 90%;
          background-color: rgba(255, 255, 255, 0.9);
          padding: 30rpx;
          border-radius: 24rpx;
          text-align: left;
          box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
          margin-bottom: 30rpx;
          border: 1px solid rgba(0, 122, 255, 0.1);

          .greeting-text {
            display: block;
            font-size: 32rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 16rpx;
          }

          .intro-text {
            display: block;
            font-size: 28rpx;
            color: #666;
            line-height: 1.6;
          }
        }

        .quick-actions {
          width: 90%;
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;

          .quick-action-item {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 20rpx;
            padding: 20rpx;
            margin-bottom: 20rpx;
            display: flex;
            align-items: center;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
            border: 1px solid rgba(0, 122, 255, 0.1);
            transition: all 0.3s ease;

            &:active {
              transform: scale(0.98);
              background-color: rgba(0, 122, 255, 0.05);
            }

            .action-icon {
              width: 60rpx;
              height: 60rpx;
              border-radius: 16rpx;
              background-color: rgba(0, 122, 255, 0.1);
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 12rpx;
              font-size: 32rpx;
            }

            text {
              font-size: 26rpx;
              color: #333;
            }
          }
        }
      }

      .message-list {
        padding: 10rpx 0;
      }

      .message-item {
        display: flex;
        margin-bottom: 30rpx;
        position: relative;

        &.message-user {
          flex-direction: row-reverse;
        }
      }

      .message-avatar {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #fff;
        flex-shrink: 0;

        &.user-avatar {
          background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
        }

        &.ai-avatar {
          background: linear-gradient(135deg, #007aff 0%, #00c6ff 100%);
        }
      }

      .message-content {
        max-width: 70%;
        padding: 20rpx 24rpx;
        border-radius: 18rpx;
        margin: 0 16rpx;
        word-break: break-word;
        font-size: 28rpx;
        line-height: 1.5;
        position: relative;
        animation: fadeIn 0.3s ease;

        &.user-content {
          background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
          color: #fff;
          border-bottom-right-radius: 4rpx;
          box-shadow: 0 4rpx 16rpx rgba(106, 17, 203, 0.2);
        }

        &.ai-content {
          background: #fff;
          color: #333;
          border-bottom-left-radius: 4rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
          border: 1px solid rgba(0, 122, 255, 0.1);
        }

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          width: 12rpx;
          height: 12rpx;
        }

        &.user-content::after {
          right: -6rpx;
          border-radius: 0 0 0 12rpx;
          background: linear-gradient(135deg, #2575fc 0%, #6a11cb 100%);
        }

        &.ai-content::after {
          left: -6rpx;
          border-radius: 0 0 12rpx 0;
          background: #fff;
          border-left: 1px solid rgba(0, 122, 255, 0.1);
          border-bottom: 1px solid rgba(0, 122, 255, 0.1);
        }
      }
    }

    .chat-bottom {
      position: relative;
      border-radius: 0 0 32rpx 32rpx;
      width: 100%;
      height: 25%;
      padding: 20rpx;
      display: flex;
      align-items: center;
      backdrop-filter: blur(10px);

      border-top: 1px solid rgba(0, 0, 0, 0.05);

      .chat-input {
        flex: 1;
        height: 120rpx;
        border-radius: 20rpx;
        padding: 20rpx 30rpx;
        margin-right: 20rpx;
        font-size: 28rpx;
        line-height: 1.5;
        box-sizing: border-box;
        background-color: rgba(255, 255, 255, 0.95);
        border: 1px solid rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;

        &:focus {
          background-color: #fff;
          box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
        }
      }

      .chat-sendBottom {
        width: 120rpx;
        height: 80rpx;
        margin: 20rpx;
        background: linear-gradient(135deg, #007aff 0%, #00c6ff 100%);
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #fff;
        transition: all 0.3s ease;
        box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);

        &.send-disabled {
          background: #ccc;
          box-shadow: none;
          opacity: 0.7;
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  .bottom {
    width: 100%;
    margin: 20rpx auto;
    text-align: center;
    font-size: 24rpx;
    color: #999999;
  }
</style>
